package com.zenithmind.note.service.impl;

import com.zenithmind.common.exception.UnauthorizedException;
import com.zenithmind.common.security.SecurityUtils;
import com.zenithmind.note.service.UserContextService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 用户上下文服务实现类
 * 
 * @author ZenithMind
 * @since 2024-01-01
 */
@Slf4j
@Service
public class UserContextServiceImpl implements UserContextService {
    
    @Override
    public String getCurrentUserId() {
        try {
            return SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            log.debug("获取当前用户ID失败: {}", e.getMessage());
            return null;
        }
    }
    
    @Override
    public String requireCurrentUserId() {
        String userId = getCurrentUserId();
        if (!StringUtils.hasText(userId)) {
            throw new UnauthorizedException("用户未登录");
        }
        return userId;
    }
    
    @Override
    public boolean isUserLoggedIn() {
        return StringUtils.hasText(getCurrentUserId());
    }
    
    @Override
    public boolean isCurrentUser(String userId) {
        if (!StringUtils.hasText(userId)) {
            return false;
        }
        String currentUserId = getCurrentUserId();
        return userId.equals(currentUserId);
    }
    
    @Override
    public List<String> getCurrentUserRoles() {
        try {
            return new java.util.ArrayList<>(SecurityUtils.getCurrentUserRoles());
        } catch (Exception e) {
            log.debug("获取当前用户角色失败: {}", e.getMessage());
            return List.of();
        }
    }
    
    @Override
    public boolean hasRole(String role) {
        if (!StringUtils.hasText(role)) {
            return false;
        }
        List<String> roles = getCurrentUserRoles();
        return roles.contains(role);
    }
    
    @Override
    public boolean isAdmin() {
        return hasRole("ADMIN") || hasRole("SUPER_ADMIN");
    }
}
